package com.lgl.interceptor;

import com.lgl.annotation.InterfaceNum;
import com.lgl.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Component
public class FangshuaInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            //获取方法中的注解，看是否有该注解
            InterfaceNum interfaceNum = handlerMethod.getMethodAnnotation(InterfaceNum.class);
            if (interfaceNum == null) {
                return true;
            }
            int seconds = interfaceNum.seconds();
            int maxcount = interfaceNum.maxcount();
            String email = request.getParameter("email");
            Integer num = (Integer) redisTemplate.opsForValue().get("cache:interface:" + email);

            if (!Objects.isNull(num)){
                if (num >= maxcount){
                    WebUtils.renderString(response,"发送验证码频繁，请稍后重试");
                    return false;
                }
                redisTemplate.opsForValue().set("cache:interface:" + email, num+1);
            }else {
                redisTemplate.opsForValue().set("cache:interface:" + email,1,seconds, TimeUnit.SECONDS);
            }

        }
        return true;
    }



}
